/**
 * 
 */
package com.sony.csl.positioning.publictransport.model.place_context.io;

import java.io.OutputStreamWriter;

import com.sony.csl.j2me.io.FileAccess;
import com.sony.csl.j2me.util.CustomStringBuffer;
import com.sony.csl.j2me.util.Logger;
import com.sony.csl.j2me.util.StringUtils;
import com.sony.csl.j2me.util.XMLUtils;
import com.sony.csl.positioning.publictransport.model.place_context.PlaceContext;


/**
 * @author mstevens
 *
 */
public class PlaceContextLogger
{

	static public String CHARACTER_ENCODING = "UTF-8";
	
	private String logFileFolderPath;
	private String logFilePath;
	private OutputStreamWriter fileWriter = null;
	private boolean logging = false;
	private long startTime;
	
	
	public PlaceContextLogger(String logFileFolderPath) throws Exception
	{
		this.logFileFolderPath = FileAccess.addFilePathPrefix(FileAccess.addTrailingSeparatorToFolderPath(logFileFolderPath));
		if(!FileAccess.doesFolderExist(logFileFolderPath, true)) //check if containing folders exists, try to create if not
			throw new Exception("The specified folder path (" + logFileFolderPath + ") is invalid!");
	}
	
	public final void startLogging() throws Exception
	{
		if(!logging)
		{
			logFilePath = logFileFolderPath + StringUtils.formatDateTime(System.currentTimeMillis(), "-", "", "T") + "_PlaceContextLog.xml";
			fileWriter = FileAccess.getFileWriter(logFilePath, FileAccess.FILE_EXISTS_STRATEGY_CREATE_RENAMED_FILE, FileAccess.FILE_DOES_NOT_EXIST_STRATEGY_CREATE, CHARACTER_ENCODING); 
			if(fileWriter == null)
				throw new Exception("fileWriter is null");
			startTime = System.currentTimeMillis();
			logging = true;
			writeHeader();
		}
	}
	
	public final void stopLogging()
	{
		if(logging)
		{
			try
			{
				writeFooter();
				logging = false;
				fileWriter.close();
				fileWriter = null;
			}
			catch(Exception e) {}
		}
	}
	
	protected final void writeToFile(String stringToWrite)
	{
		if(logging)
		{
			try
			{
				fileWriter.write(stringToWrite);
				fileWriter.flush();
			}
			catch(Exception e)
			{
				Logger.logLine("Could not write to PlaceContext log file (Exception: " + e.getMessage() + ")");
				stopLogging();
			}
		}
	}
	
	protected void writeHeader()
	{
		CustomStringBuffer bff = new CustomStringBuffer();
		//XML file headers
		bff.appendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		bff.appendLine("<PlaceContextLog startTime=\"" + XMLUtils.timeDateValue(startTime) + "\">");
		//Write to file
		writeToFile(bff.toString());
	}
	
	protected void writeFooter()
	{
		writeToFile("</PlaceContextLog>");
	}	

	public void writePlaceContext(PlaceContext placeContext)
	{
		if(logging && placeContext != null)
			writeToFile("\t" + placeContext.toXML() + "\n");
	}

	/**
	 * @return the logging
	 */
	public boolean isLogging()
	{
		return logging;
	}
		
}

